package com.lp.biz.operations.service.impl;

import com.github.pagehelper.PageInfo;
import com.lp.biz.identity.service.BizIdentityService;
import com.lp.biz.operations.model.entity.BizAuthApply;
import com.lp.biz.operations.mapper.BizAuthApplyMapper;
import com.lp.biz.operations.model.vo.ApplyList;
import com.lp.biz.operations.service.BizAuthApplyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lp.common.entity.PageParams;
import com.lp.common.exception.BaseException;
import com.lp.common.utils.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static com.lp.common.constant.CommonConstant.NEGATE;

/**
 * @program: backend
 * @description: BizAuthApply 服务实现类
 * @author Ke.Song
 * @since 2024-08-08 23:28:07
 */
@Service
public class BizAuthApplyServiceImpl extends ServiceImpl<BizAuthApplyMapper, BizAuthApply> implements BizAuthApplyService {

    @Autowired
    private BizIdentityService identityService;

    @Override
    public CommonResult getApplyList(PageParams query) {
        List<ApplyList> applyList = baseMapper.getApplyList();
        PageInfo<ApplyList> pageInfo = new PageInfo<>();
        pageInfo.setTotal(applyList.size());
        pageInfo.setPageNum(query.getPage());
        pageInfo.setSize(query.getSize());
        pageInfo.setList(applyList.stream().skip(query.getSize() * (query.getPage() - 1L)).limit(query.getSize()).toList());
        return CommonResult.restPage(pageInfo);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void updateApplyStatus(Integer applyId, boolean action) {
        BizAuthApply apply = getById(applyId);
        if (apply == null) {
            throw new BaseException("申请记录不存在");
        } else if (!apply.getStatus().equals(NEGATE)) {
            throw new BaseException("已审批");
        }
        apply.setStatus(action ? 1: 2);
        updateById(apply);
        if (action) {
            identityService.addIdentity(apply.getMemberId(), apply.getBizIdentityId());
        }
    }
}
